//
//  ZLPostImageController.swift
//  新浪微博
//
//  Created by 朱玉龙 on 16/10/7.
//  Copyright © 2016年 朱玉龙. All rights reserved.
//

import UIKit

private let plusCellID = "plusCellID"
var images: [UIImage]? = [UIImage]()


class ZLPostImageController: UICollectionViewController {
    
    var itemHidden: (() -> ())?
    var textViewBlock: (() -> ())?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        self.collectionView!.register(ZLPlusCell.self, forCellWithReuseIdentifier: plusCellID)
        imagePicker.delegate = self
        
       
    }
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }
    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images?.count ?? 0
        
        return count == 5 ? 5 : count + 1
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: plusCellID, for: indexPath) as! ZLPlusCell
        
        cell.delegate = self
        
        if indexPath.item != images?.count {
            
            cell.indexPath = indexPath
            
            cell.removeBtn.isHidden = false
            
        } else {
            
            cell.removeBtn.isHidden = true
            cell.indexPath = nil
        }
        
        
        return cell
    }
    
    lazy var imagePicker: UIImagePickerController = UIImagePickerController()
    
}



protocol ZLPlusCellDelegate: NSObjectProtocol {
    
    func addBtnClick()
    
    func removeBtnClick(cell: ZLPlusCell)
    
}


class ZLPlusCell: UICollectionViewCell {
    
    weak var delegate: ZLPlusCellDelegate?
    
    var indexPath: IndexPath? {
        
        didSet {
            
            if indexPath != nil {
                
                let image = images?[(indexPath?.item)!]
                addBtn.setImage(image, for: .normal)
            } else {
                
                addBtn.setImage(nil, for: .normal)
            }
            
        
            let backImage: UIImage? = (indexPath == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            
           addBtn.setBackgroundImage(backImage, for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        contentView.backgroundColor = randomColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView.snp.edges)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.top.trailing.equalTo(self.contentView)
            make.height.width.equalTo(24)
        }
        
    }
    
    lazy var addBtn: UIButton = {
        let addBtn = UIButton()
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        addBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .highlighted)
        addBtn.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        return addBtn
    }()
    
    lazy var removeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        btn.addTarget(self, action: #selector(removeBtnClick), for: .touchUpInside)
        return btn
    }()
    
    @objc private func addBtnClick() {
        
        delegate?.addBtnClick()
        
    }
    @objc private func removeBtnClick() {
        
        delegate?.removeBtnClick(cell:self)
        
    }
}

extension ZLPostImageController: ZLPlusCellDelegate {
    
   
    
    
    func addBtnClick() {
        
        if images?.count == 5 {
            return
        }
        
        present(imagePicker, animated: true, completion: nil)
    
        textViewBlock!()
        
    }
    
    func removeBtnClick(cell: ZLPlusCell) {
        
        images?.remove(at: (cell.indexPath?.item)!)
        
        self.collectionView?.reloadData()
        
        self.view.isHidden = images?.count == 0
        
        itemHidden!()
    }
}
//MARK: imagePick代理方法
extension ZLPostImageController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        images?.append(image.compressImage(width: 600))
        self.dismiss(animated: true, completion: nil)
        self.collectionView?.reloadData()
        self.view.isHidden = images?.count == 0
        itemHidden!()
    }
    
    
    
}

